# @Time    : 2022/2/3 10:11
# @Author  : junbaibai
# @File    : sqlite3utils.py
import contextlib
import sqlite3
import typing

from src.utils.logger import Logger

logger = Logger(__name__)


class DbUtils:
    __slots__ = ["_conn"]

    def __init__(self, database="static/hoi.db"):
        self._conn = sqlite3.connect(database, check_same_thread=False)

    def insert(self, table, key, value: typing.Iterator):
        values = ""
        for i in value:
            if i is None:
                values += "null"
            elif isinstance(i, str):
                values += f"'{i}'"
            else:
                values += str(i)
            values += ","
        values = values[:-1]
        statement = f"""insert into {table} ({','.join(key)}) values ({values})"""
        logger.i(statement)
        c = self._conn.cursor()
        cursor = c.execute(statement)
        self._conn.commit()
        c.close()

    @contextlib.contextmanager
    def select(self, table, key, order_by="", group_by="") -> sqlite3.Cursor:
        if order_by != "":
            order_by = f"order by {order_by}"
        statements = f"""select {','.join(key)} from {table} {order_by}"""
        c = self._conn.cursor()
        cursor = c.execute(statements)
        self._conn.commit()
        yield c
        c.close()

    @contextlib.contextmanager
    def execute(self, statements):
        c: sqlite3.Cursor = self._conn.cursor()
        c.execute(statements)
        self._conn.commit()
        yield c
        c.close()

    def __del__(self):
        self.close()

    def close(self):
        self._conn.close()


# 单例模式
dbUtil = DbUtils()
logger.i(dbUtil)
